package be.kdg.bombermanunlimited.client.network.packet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ConversionTools {
	public static byte[] serialize(Object object) {
		try {
			// // Serialize to a byte array
			// maak bytearrayoutputstream
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			// maak objectoutputstream die data wegschrijft naar
			// Byteoutputstream
			ObjectOutputStream out = new ObjectOutputStream(bos);
			// schrijf het object weg
			out.writeObject(object);
			// outputstream niet meer nodig, sluiten.
			out.close();

			// Get the bytes of the serialized object
			// System.out.println("Bytestream generated");
			return bos.toByteArray();
		} catch (Exception i) {
			i.printStackTrace();
			// System.out.println("Couldn't generate bytestream!");
			return null;
		}
	}

	public static Object deserialize(byte[] byteArray) {
		ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
		// ObjectInputStream in = new ObjectInputStream(bis);

		Object object;
		ObjectInputStream in2;
		try {
			in2 = new ObjectInputStream(bis);
			object = (Object) in2.readObject();
			in2.close();
		} catch (IOException e) {
			// System.out.println("Couldn't generate object!");
			return null;
		} catch (ClassNotFoundException e) {

			// System.out.println("Couldn't generate object!");
			return null;
		}
		return object;

	}
}
